const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const BadRequestError = require('../../utils/errors').BadRequestError;
const UnauthorizedError = require('../../utils/errors').UnauthorizedError;
const NotFoundError = require('../../utils/errors').NotFoundError;
const success = require('../../utils/responses').success;
const failure = require('../../utils/responses').failure;
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

// 假设你的应用有对应的环境变量 SECRET 用于 JWT 签名，这里需要确保已正确设置
const SECRET = process.env.SECRET;

// 连接 MongoDB 数据库，替换为你自己的真实连接字符串
mongoose.connect('mongodb://localhost:27017/control-book', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// 管理员登录
router.post('/sign_in', async (req, res) => {
  try {
      const { login, password } = req.body;
      console.log(login, password);

      if (!login) {
          throw new BadRequestError('邮箱/用户名必须填写。');
      }

      if (!password) {
          throw new BadRequestError('密码必须填写。');
      }

      // 通过email或username，查询用户是否存在
      const user = await mongoose.models.User.findOne({
          $or: [
              { email: login },
              { username: login }
          ]
      });

      if (!user) {
          throw new NotFoundError('用户不存在，无法登录。');
      }

      const isPasswordValid = bcrypt.compareSync(password, user.password);
      console.log(isPasswordValid);
      if (!isPasswordValid) {
          throw new UnauthorizedError('密码错误。');
      }
      console.log(user);

      const token = jwt.sign({
          userId: user._id
      }, SECRET, { expiresIn: '30d' });

      success(res, '登录成功。', { token, login, avatar: user.avatar, nickname: user.nickname, id: user._id, role: user.role, username: user.username });
  } catch (error) {
    console.error(error);
      failure(res, error);
  }
});

module.exports = router;